import { _decorator, Button, Component, director, game, instantiate, Node, Sprite, tween, Vec3 } from 'cc';
import ResourceManger from './ResourceManger';
import { AssetType, Clips } from './Enums';
import { AudioManger } from './AudioManger';
import { Tools } from './Tools';
import { Global } from './Global';
import { ResourcePool } from './ResourcePool';
import { LevelAction } from './LevelAction';
import { WxPlatform } from './ad/WxPlatform';
import { LayerAction } from './LayerAction';
import { ElementAction } from './ElementAction';
import { UnitAction } from './UnitAction';
const { ccclass, property } = _decorator;

@ccclass('HomeAction')
export class HomeAction extends Component {
    @property({ type: Node }) logo: Node = null;
    @property(Sprite) load: Sprite = null;
    @property({ type: Node }) btns_layer: Node = null;

    private isload = true;
    private load_num = 0;

    @property({ type: String }) ad_intersitial_id: string;
    @property({ type: String }) ad_video_id: string;
    @property({ type: String }) ad_banner_id: string;

    onLoad() {
        // game.frameRate = 60;
    }

    async start() {
        this.btns_layer.active = false;
        Global.ad_intersitial_id = this.ad_intersitial_id;
        Global.ad_video_id = this.ad_video_id;
        Global.ad_banner_id = this.ad_banner_id;
        WxPlatform.ins.wechat_setting();

        try {
            await this.loadRes();
        } catch (error) {
            console.error("资源加载失败:", error);
        }
    }

    async loadRes() {
        return new Promise<void>(async (resolve) => {
            director.preloadScene("main", () => {
                console.log(">>> main scene preload completed!!");
                this.show_btns();
            });
            await ResourceManger.instance.load_bundle("bundle", 0.2);
            await ResourceManger.instance.load_resource("bundle", AssetType.Prefab, 0.6);
            await ResourceManger.instance.load_resource("bundle", AssetType.Sound, 0.22);
            resolve();
        });
    }

    start_game() {
        AudioManger.instance.playSound(Clips.btn_1);
        director.loadScene("main");
    }

    show_btns() {
        this.load_num++;
        if (this.load_num >= 2) {
            this.load.node.parent.parent.active = false;
            this.btns_layer.active = true;

            // 判断是否有激活按钮
            const hasActiveBtn = this.btns_layer.children.some(btn => btn.active);
            if (!hasActiveBtn) {
                this.start_game();
            }
        }
    }

    update(deltaTime: number) {
        if (!this.isload) return;
        this.load.fillRange = Global.loading_rate;
        if (Global.loading_rate >= 0.99) {
            this.isload = false;
            this.show_btns();
        }
    }

    check_lvl_data() {
        this._unit_data();
        this._lvl_data();

        let arr = ResourcePool.instance.get_prefabs_for_unit();
        console.log(">>> 预制体列表:", arr);
    }

    private check_pin_num(pin_total: number): string {
        const d = pin_total % 3;
        if (d === 1) return "数据错误，关卡钉子（空洞）多了1个";
        if (d === 2) return "数据错误，关卡钉子（空洞）多了2个";
        return "没问题";
    }

    private _unit_data() {
        console.log("-------------------- unit检查开始 --------------------");
        const arr = ResourcePool.instance.get_prefabs_for_unit();

        arr.forEach(unitPrefab => {
            const lvl_node = instantiate(unitPrefab);
            const pin_total = lvl_node.getComponent(UnitAction).get_hole_num();
            const msg = this.check_pin_num(pin_total);
            console.log(`${lvl_node.name} >>> 钉子总数: ${pin_total}, 提示: ${msg}`);
        });
    }

    private _lvl_data() {
        console.log("-------------------- 等级数据安全性 --------------------");

        for (let lvl = 1; lvl <= 150; lvl++) {
            console.log(`${lvl} lvl >>>>>`);
            const level_prefab = ResourcePool.instance.get_prefab(`lvl_${lvl}`);
            if (!level_prefab) {
                console.log(`${lvl} 没有这个等级，停止检查`);
                break;
            }

            const lvl_node = instantiate(level_prefab);
            const pin_total = lvl_node.getComponent(LevelAction).get_hole_num();
            const msg = this.check_pin_num(pin_total);
            console.log(`钉子总数: ${pin_total}, 提示: ${msg}`);

            lvl_node.children.forEach(unit_node => {
                console.log(`单元检查: ${unit_node.name}`);

                if (!unit_node.active) {
                    console.warn(`错误: unit node ${unit_node.name} 是隐藏的`);
                }

                const unit_action = unit_node.getComponent(UnitAction);
                if (!unit_action) {
                    console.warn(`错误: unit action 错误 - ${unit_node.name}`);
                }

                unit_node.children.forEach(layer_node => {
                    if (!layer_node.active) {
                        console.warn(`错误: layer node ${layer_node.name} 是隐藏的`);
                    }
                    const layer_action = layer_node.getComponent(LayerAction);
                    if (!layer_action) {
                        console.warn(`错误: layer action 错误 - ${layer_node.name}`);
                    }

                    layer_node.children.forEach(ele_node => {
                        if (!ele_node.active) {
                            console.warn(`错误: element node ${ele_node.name} 是隐藏的`);
                        }
                        if (!ele_node.getComponent(ElementAction)) {
                            console.warn(`错误: element action 错误 - ${ele_node.name}`);
                        }
                    });
                });
            });
        }
    }
}
